package leetcode.day_2020_11_9_11_15;

public class L_4 {
    public static void main(String[] args) {
        int[] nums1 = {1, 2};
        int[] nums2 = {3, 4};
        System.out.println(findMedianSortedArrays(nums1, nums2));
    }

    public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int nums1L = nums1.length;
        int nums2L = nums2.length;
        int[] totalNum = new int[nums1L+nums2L];
        int i=0, j=0, k=0;
        while(i<nums1L && j<nums2L) {
            if(nums1[i] < nums2[j]) {
                totalNum[k] = nums1[i];
                i++;
            } else if(nums1[i] > nums2[j]) {
                totalNum[k] = nums2[j];
                j++;
            }else if(nums1[i] == nums2[j]) {
                totalNum[k] = nums1[i];
                totalNum[++k] = nums2[j];
                i++; j++;
            }
            k++;
        }

        if(j == nums2L) {
            while (i<nums1L) {
                totalNum[k++] = nums1[i++];
            }
        }else {
            while (j<nums2L) {
                totalNum[k++] = nums2[j++];
            }
        }

        int mid = (nums1L+nums2L) / 2 ;
        if((nums1L + nums2L) % 2 == 0) {
            return ((double)totalNum[mid] +(double)totalNum[mid-1])/2;
        } else {
            return totalNum[mid];
        }
    }
}
